package com.peycard.service;

import java.util.ArrayList;
import java.util.Collection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.peycard.common.PortalUserDTO;
import com.peycard.util.Utils;

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(UserDetailsServiceImpl.class);

	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		User user = null;
		try {
			LoginService loginService = new LoginService();
			PortalUserDTO currentUser = loginService.loginRequest(username);

			if (currentUser == null) {
				LOGGER.debug("Usuario no encontrado");
				throw new UsernameNotFoundException("Usuario no encontrado",
						null);
			}
			LOGGER.info("**[" + currentUser.toString() + "]**");
			String password = Utils.encryptPassword(currentUser.getPassword());
			boolean enabled = currentUser.getIsActive() == 0 ? true : false;
			boolean accountNotExpired = currentUser.getIsActive() == 0 ? true
					: false;
			boolean credentialNotExpired = currentUser.getIsActive() == 0 ? true
					: false;
			boolean accountNotLocked = currentUser.getIsActive() == 0 ? true
					: false;

			Collection<GrantedAuthority> listAuthorities = new ArrayList<GrantedAuthority>();
			listAuthorities.add(new GrantedAuthorityImpl(currentUser.getRol()));
			user = new User(username, password, enabled, accountNotExpired,
					credentialNotExpired, accountNotLocked, listAuthorities);

		} catch (Exception ex) {
			LOGGER.error("La conexión no pudo completarse, error generico.", ex);
		}
		return user;
	}
}
